<template>
  <TresCanvas window-size clear-color="#82DBC5">
    <TresPerspectiveCamera :position="[0, 0, 8]" />
    <!-- <TresGridHelper /> -->
    <!-- <TresAxesHelper /> -->
    <OrbitControls 
      ref="oCtrRef"
      :auto-rotate="false" :auto-rotate-speed="1"
      enable-damping :min-distance="1" :max-distance="16"
      :max-polar-angle="Math.PI*3/4" :min-polar-angle="Math.PI/4"
      :rotate-speed="-1"
      @change="onCameraChange"
    />
    <!-- <CameraControls make-default :min-distance="1" :max-distance="16" /> -->
    <TresAmbientLight :intensity="3" />
    <SkySphere @updateCtrl="updateOrbitCtrl" />
  </TresCanvas>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import { TresCanvas } from '@tresjs/core'
import { OrbitControls } from '@tresjs/cientos'
import SkySphere from './SkySphere.vue'
import { storeToRefs } from 'pinia'
import { useRoomStore } from '@/stores/useRoomStore'

const oCtrRef=ref()
const store = useRoomStore()
const { room } = storeToRefs(store)

function onCameraChange(evt: any) {
  const x = evt.object.position.x
  const z = evt.object.position.z
  let angle = Math.atan2(x,z) * 180 / Math.PI
  room.value!.mapPos.rotate = -angle
}
function updateOrbitCtrl(){
  const ctrl=oCtrRef.value?.value
  if(!ctrl) return
  const rad = -room.value!.mapPos.rotate*Math.PI/180
  const _camera=ctrl.object
  _camera.position.z=8*Math.cos(rad)
  _camera.position.x=8*Math.sin(rad)
  ctrl.update()
}
</script>

<style scoped></style>